<?php
class Pauler_Searchseo_Manage_SearchseoController extends Mage_Adminhtml_Controller_action{

    protected function _initAction(){
        $this->loadLayout()
            ->_setActiveMenu('searchseo/list');
        return $this;
    }
    public function IndexAction()
    {
        $this->_initAction()
            ->renderLayout();
    }
    public function editAction(){
        $id  = $this->getRequest()->getParam('id');
        $model  = Mage::getModel('searchseo/query')->load($id);
        if ($model->getId() || $id == 0) {
            $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
            if (!empty($data)) {
                $model->setData($data);
            }

            // $storeId    = (int) $this->getRequest()->getParam('store');
            $category = Mage::getModel('catalog/category');
            // $category->setStoreId($storeId);
            $categoryId = $model->getRedirect(); 
            if ($categoryId) {
                $category->load($categoryId);
                // if ($storeId) {
                //     $rootId = Mage::app()->getStore($storeId)->getRootCategoryId();
                //     if (!in_array($rootId, $category->getPathIds())) {
                // load root category instead wrong one
                //         if ($getRootInstead) {
                //             $category->load($rootId);
                //        }
                //        else {
                //            $this->_redirect('*/*/', array('_current'=>true, 'id'=>null));
                //              return false;
                //        }
                //    }
                //   }
            }
            Mage::register('category', $category);
            Mage::register('current_category', $category);
            Mage::register('searchseo_data', $model);

            $this->loadLayout();
            $this->_setActiveMenu('searchseo/list');

            //$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

            $this->_addContent($this->getLayout()->createBlock('searchseo/manage_searchseo_edit'))
                ->_addLeft($this->getLayout()->createBlock('searchseo/manage_searchseo_edit_tabs'));

            $this->renderLayout();
        }else {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('searchseo')->__('search does not exist'));
            $this->_redirect('*/*/');
        }
    }
    public function newAction()
    {
        $id = $this->getRequest()->getParam('id');
        $model = Mage::getModel('searchseo/query')->load($id);
        $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
        if (!empty($data)) {
            $model->setData($data);
        } 
        Mage::register('searchseo_data',$model);
        $this->loadLayout();
        $this->_setActiveMenu('searchseo/list');  
        $this->_addContent($this->getLayout()->createBlock('searchseo/manage_searchseo_edit'))
            ->_addLeft($this->getLayout()->createBlock('searchseo/manage_searchseo_edit_tabs'));
        $this->renderLayout();   
    }
    public function saveAction(){

        if($data = $this->getRequest()->getPost()){
            $model = Mage::getModel('searchseo/query');
            $model->load($this->getRequest()->getParam('id'));
            try{
                $model->addData($data['searchseo']);
                Mage::register('searchseo_data', $model);
                if(!$data['searchseo']['redirect']){
                    $collection = Mage::getModel('catalog/category')->getCollection();
                    $collection->addAttributeToSelect('name')
                        ->addLevelFilter(1);
                    $i=0;
                    foreach($collection as $rootcategory){
                        // var_dump($rootcategory->getId(), $rootcategory->getPath(),count(explode('/',$rootcategory->getPath())) ==2);
                        $i++;
                        if( $i == 3){
                            $searchCategory = $rootcategory;
                            break;
                        }
                    }
                    if(!$searchCategory || !$searchCategory->getId()){
                        $searchCategory = $this->_saveCategory();

                    }
                    Mage::register('parent_category', $searchCategory); 
                } 
                $Category = $this->_saveCategory();


                $model->addData(array('redirect'=>$Category->getId()));
                $model->save();
                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('searchseo')->__('Search  was successfully saved'));   
                Mage::getSingleton('adminhtml/session')->setFormData(false);
                // if($this->getRequest()->getParam('back')){
                //      $this->_redirect('*/*/edit',array('id'=>$model->getId()) );
                //      return;
                //  }
                // $this->_redirect('*/*/');
                // return;
            }catch(Exception $e){
                 Mage::getSingleton('adminhtml/session')->addError($e->getMessage);
                 Mage::getSingleton('adminhtml/session')->setFormData($data);
                 //$this->_redirect('*/*/edit',array('id'=>$this->getRequest()->getParam('id') ) );
                //  return;
            }
        }
        // Mage::getSingleton('adminhtml/session')->addError(Mage::helper('course')->__('Unable to find course to save'));
        //$this->_redirect('*/*/');
        //  $url = $this->getUrl('*/*/edit', array('_current' => true, 'id' => $category->getId()));
        $url = $this->getUrl('*/*/edit', array('_current' => true, 'id' => $model->getId()));
        $this->getResponse()->setBody(
            '<script type="text/javascript">parent.updateContent("' . $url . '", {}, false);</script>'
        );
    }
    public function _saveCategory()
    {
        if (!$category = $this->_initCategory()) {
            return;
        }

        $storeId = $this->getRequest()->getParam('store');
        if ($data = $this->getRequest()->getPost()) {
            $category->addData($data['general']);
            if (!$category->getId()) {
                // $parentId = $this->getRequest()->getParam('parent');
                $parentCategory = Mage::registry('parent_category');
                if (!$parentCategory) {
                    if ($storeId) {
                        $parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
                    }
                    else {
                        $parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
                    }
                    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
                }

                $category->setPath($parentCategory->getPath());
            }

            /**
             * Process "Use Config Settings" checkboxes
             */
            if ($useConfig = $this->getRequest()->getPost('use_config')) {
                foreach ($useConfig as $attributeCode) {
                    $category->setData($attributeCode, null);
                }
            }

            /**
             * Create Permanent Redirect for old URL key
             */
            if ($category->getId() && isset($data['general']['url_key_create_redirect']))
                // && $category->getOrigData('url_key') != $category->getData('url_key')
            {
                $category->setData('save_rewrites_history', (bool)$data['general']['url_key_create_redirect']);
            }

            $category->setAttributeSetId($category->getDefaultAttributeSetId());

            if (isset($data['category_products']) &&
                !$category->getProductsReadonly()) {
                    $products = array();
                    parse_str($data['category_products'], $products);
                    $category->setPostedProducts($products);
                }

            Mage::dispatchEvent('catalog_category_prepare_save', array(
                'category' => $category,
                'request' => $this->getRequest()
            ));

            /**
             * Proceed with $_POST['use_config']
             * set into category model for proccessing through validation
             */
            $category->setData("use_post_data_config", $this->getRequest()->getPost('use_config'));
            $validate = $category->validate();
            if ($validate !== true) {
                foreach ($validate as $code => $error) {
                    if ($error === true) {
                        Mage::throwException(Mage::helper('catalog')->__('Attribute "%s" is required.', $category->getResource()->getAttribute($code)->getFrontend()->getLabel()));
                    }
                    else {
                        Mage::throwException($error);
                    }
                }
            }

            /**
             * Check "Use Default Value" checkboxes values
             */
            if ($useDefaults = $this->getRequest()->getPost('use_default')) {
                foreach ($useDefaults as $attributeCode) {
                    $category->setData($attributeCode, false);
                }
            }

            /**
             * Unset $_POST['use_config'] before save
             */
            $category->unsetData('use_post_data_config');
            $category->save();
            return $category;

        }
    }
    protected function _initCategory($getRootInstead = false)
    {

        //$categoryId = (int) $this->getRequest()->getParam('id',false);
        $categoryId = Mage::registry('searchseo_data')->getRedirect();
        $storeId    = (int) $this->getRequest()->getParam('store');
        $category = Mage::getModel('catalog/category');
        $category->setStoreId($storeId);

        if ($categoryId) {
            $category->load($categoryId);
        }

        if ($activeTabId = (string) $this->getRequest()->getParam('active_tab_id')) {
            // Mage::getSingleton('admin/session')->setActiveTabId($activeTabId);
        }
        Mage::register('category', $category);
        Mage::register('current_category', $category);
        return $category;
    }

    public function gridAction()
    {

        $model = Mage::getModel('searchseo/query');
        $model->load($this->getRequest()->getParam('id'));
        $model->addData($data['searchseo']);
        Mage::register('searchseo_data', $model);
        if (!$category = $this->_initCategory(true)) {
            return;
        }
        $this->getResponse()->setBody(
            $this->getLayout()->createBlock('adminhtml/catalog_category_tab_product')->toHtml()
        );
    }
    public function deleteAction() {
        if( $this->getRequest()->getParam('id') > 0 ) {
            try {
                $model = Mage::getModel('searchseo/query');

                $model->setId($this->getRequest()->getParam('id'))
                    ->delete();
                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Search was successfully deleted'));
                $this->_redirect('*/*/');
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            }
        }
        $this->_redirect('*/*/');
    }
    public function massDeleteAction() {
        $courseIds = $this->getRequest()->getParam('searchseo');
        if(!is_array($courseIds)) {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select Search(s)'));
        } else {
            try {
                foreach ($courseIds as $courseId) {
                    $model = Mage::getModel('searchseo/query')->load($courseId);
                    $model->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were successfully deleted', count($courseIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }
    public function massStatusAction() {
        $courseIds = $this->getRequest()->getParam('searchseo');
        if(!is_array($courseIds)) {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select Search(s)'));
        } else {
            try {
                foreach ($courseIds as $courseId) {
                    $model = Mage::getModel('searchseo/query')->load($courseId)
                        ->setIsActive($this->getRequest()->getParam('is_active'))
                        ->setIsMassupdate(true)
                        ->save();

                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were successfully updated', count($courseIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }
}
